/*
 * @Author: your name
 * @Date: 2020-09-21 16:08:24
 * @LastEditTime: 2020-09-23 15:20:13
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \PipeOneMap_WebClient\src\app\shared\directive\drag.directive.ts
 */
import { Directive, ElementRef, OnInit, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[appDrag]'
})
export class DragDirective implements OnInit {
  constructor(public el: ElementRef) {
  }
  public isDown = false;
  @Input() isDrag = true;
  public disX; // 记录鼠标点击事件的位置 X

  public disY; // 记录鼠标点击事件的位置 Y


  @Input() totalOffsetX = 0; // 记录总偏移量 X轴
  @Input() totalOffsetY = 0; // 记录总偏移量 Y轴

  // 点击事件
  @HostListener('mousedown', ['$event']) onMousedown(event) {
    if (this.isDrag) {
      //  console.log('mousedown', event);
      this.isDown = true;
      this.disX = event.clientX;
      this.disY = event.clientY;
     }
 }

  // 监听document移动事件事件
  @HostListener('document:mousemove', ['$event']) onMousemove(event) {
   // console.log('mousemove', event);
    // 判断该元素是否被点击了。
    if (this.isDown) {
      this.el.nativeElement.style.left = this.totalOffsetX + event.clientX - this.disX + 'px';
      this.el.nativeElement.style.top = this.totalOffsetY + event.clientY - this.disY + 'px';
    }
  }

  // 监听document离开事件
  @HostListener('document:mouseup', ['$event']) onMouseup(event) {
   // console.log('mouseup', event);
    // 只用当元素移动过了，离开函数体才会触发。
    if (this.isDown) {
     // console.log('fail');
      this.totalOffsetX += event.clientX - this.disX;
      this.totalOffsetY += event.clientY - this.disY;
      this.isDown = false;
    }
  }

  ngOnInit() {
    this.el.nativeElement.style.position = 'absolute';
  }
}
